/**
=========================================================
* Material Dashboard 2 React - v2.2.0
=========================================================

* Product Page: https://www.creative-tim.com/product/material-dashboard-react
* Copyright 2023 Creative Tim (https://www.creative-tim.com)

Coded by www.creative-tim.com

 =========================================================

* The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
*/

// @mui material components
import Grid from "@mui/material/Grid";
import Divider from "@mui/material/Divider";

// @mui icons
import FacebookIcon from "@mui/icons-material/Facebook";
import TwitterIcon from "@mui/icons-material/Twitter";
import InstagramIcon from "@mui/icons-material/Instagram";

// Material Dashboard 2 React components
import MDBox from "components/MDBox";
import MDTypography from "components/MDTypography";

// Material Dashboard 2 React example components
import DashboardLayout from "examples/LayoutContainers/DashboardLayout";
import DashboardNavbar from "examples/Navbars/DashboardNavbar";
import Footer from "examples/Footer";
import ProfileInfoCard from "examples/Cards/InfoCards/ProfileInfoCard";
import ProfilesList from "examples/Lists/ProfilesList";
import DefaultProjectCard from "examples/Cards/ProjectCards/DefaultProjectCard";

// Overview page components
import Header from "layouts/profile/components/Header";
import PlatformSettings from "layouts/profile/components/PlatformSettings";

// Data
import profilesListData from "layouts/profile/data/profilesListData";

// Images
import homeDecor1 from "assets/images/home-decor-1.jpg";
import homeDecor2 from "assets/images/home-decor-2.jpg";
import homeDecor3 from "assets/images/home-decor-3.jpg";
import homeDecor4 from "assets/images/home-decor-4.jpeg";
import team1 from "assets/images/team-1.jpg";
import team2 from "assets/images/team-2.jpg";
import team3 from "assets/images/team-3.jpg";
import team4 from "assets/images/team-4.jpg";

import { useEffect, useState } from "react";
import axios from "axios";
import { Dialog, DialogActions, DialogContent, DialogTitle } from "@mui/material";
import TextField from "@mui/material/TextField";
import Button from "@mui/material/Button";
import header from "layouts/profile/components/Header";
import MDButton from "../../components/MDButton";
import DataTable from "../../examples/Tables/DataTable";
import MDInput from "../../components/MDInput";

function Overview() {
  const [nickname, setNickname] = useState([]);

  const [email, setEmail] = useState([]);

  const [personalIntroduction, setPersonalIntroduction] = useState([]);

  const [newBio, setNewBio] = useState("");

  const [open, setOpen] = useState(false); // 控制弹窗
  const [newEmail, setNewEmail] = useState([]);
  const [oldPassword, setOldPassword] = useState([]);
  const [newPassword, setNewPassword] = useState([]);
  const [rePassword, setRePassword] = useState([]);
  const [openPassword, setOpenPassword] = useState(false);
  const token = localStorage.getItem("authToken");

  const [role, setRole] = useState(0);
  //日志信息
  const [logData, setLogData] = useState([]);
  //是否显示
  const [showTable, setShowTable] = useState(false);
  const [showTable1, setShowTable1] = useState(false);
  const [userData, setUserData] = useState([]);
  const columns = [
    { Header: "用户ID", accessor: "user_id", align: "center" },
    { Header: "操作", accessor: "operate", align: "center" },
    { Header: "时间", accessor: "time", align: "center" },
  ];

  const columns1 = [
    { Header: "ID", accessor: "id", align: "left" },
    { Header: "状态", accessor: "status", align: "center" },
    { Header: "昵称", accessor: "nickname", align: "center" },
    { Header: "个人简介", accessor: "personalIntroduction", align: "center" },
  ];

  const [filterUserId, setFilterUserId] = useState("");
  const [filterOperate, setFilterOperate] = useState("");
  const [sortOrder, setSortOrder] = useState("asc");

  const fetchUserData = async () => {
    try {
      const response = await axios.get("http://localhost:8848/user/findAll", {
        headers: {
          Authorization: `Bearer ${token}`,
        },
        withCredentials: true,
      });
      const formattedData1 = response.data.map((item) => ({
        id: item.id,
        status: item.status,
        nickname: item.nickname,
        personalIntroduction: item.personalIntroduction,
      }));
      setUserData(formattedData1);
      setShowTable1(true);
    } catch (error) {
      console.error("获取用户数据失败", error);
    }
  };

  const fetchLogs = async () => {
    try {
      const res = await axios.get("http://localhost:8848/logs", {
        headers: {
          Authorization: `Bearer ${token}`,
        },
        withCredentials: true,
      });
      const formattedData = res.data.map((item) => ({
        user_id: item.user_id,
        operate: item.operate,
        time: item.time,
      }));
      setLogData(formattedData);
      setShowTable(true);
    } catch (err) {
      console.error("日志获取失败:", err);
    }
  };
  // console.log(token);
  useEffect(() => {
    const token = localStorage.getItem("authToken");
    const fetchData = async () => {
      try {
        const response = await axios.get("http://localhost:8848/user/userInfo", {
          headers: {
            Authorization: `Bearer ${token}`,
          },
          withCredentials: true,
        });
        const jsonData =
          typeof response.data === "string" ? JSON.parse(response.data) : response.data;
        console.log("response data:", response.data);
        console.log("response nickname data:", jsonData.data.nickname);
        console.log("response email data:", jsonData.data.email);
        console.log("response personalIntroduction data:", jsonData.data.personalIntroduction);
        console.log("response role is:", jsonData.data.role);
        if (response.data) {
          setNickname(jsonData.data.nickname);
          setEmail(jsonData.data.email);
          setPersonalIntroduction(jsonData.data.personalIntroduction);
          setRole(jsonData.data.role);
        } else {
          console.log("User data is not available");
        }
        await axios.post(
          "http://localhost:8848/addLog",
          {
            operate: "进入了个人主页",
          },
          {
            headers: { Authorization: `Bearer ${token}` }, // 发送请求时携带 Token
            withCredentials: true,
          }
        );
      } catch (error) {
        console.error("获取数据失败", error);
      }
    };
    fetchData();
  }, []);

  const handleOpen = () => {
    setNewBio(personalIntroduction); // 默认填充当前简介
    setNewEmail(email);
    setOpen(true);
  };
  const handleOpenPassword = () => {
    setOpenPassword(true);
  };
  const handleClose = () => setOpen(false);

  const handleClosePassword = () => setOpenPassword(false);

  const handleSave = async () => {
    axios
      .put(
        "http://localhost:8848/user/updatePersonalIntroductionAndEmail",
        { bio: newBio, email: newEmail },
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      )
      .then(() => {
        window.location.reload(); // 提交成功后刷新页面
      })
      .catch((error) => console.error("更新简介失败:", error));
    await axios.post(
      "http://localhost:8848/addLog",
      {
        operate: "更改了个人介绍与邮箱",
      },
      {
        headers: { Authorization: `Bearer ${token}` }, // 发送请求时携带 Token
        withCredentials: true,
      }
    );
  };

  const handleKeyDown = (event) => {
    if (event.key === "Enter") {
      event.preventDefault(); // 防止默认换行
      handleSave();
    }
  };

  const ChangePassword = () => {
    console.log(oldPassword);
    const response = axios.patch(
      "http://localhost:8848/user/updatePwd",
      { oldPassword: oldPassword, newPassword: newPassword, rePassword: rePassword },
      {
        headers: {
          Authorization: `Bearer ${token}`,
        },
      }
    );
    setOpenPassword(false);
    alert(response);
    axios.post(
      "http://localhost:8848/addLog",
      {
        operate: "更改了密码",
      },
      {
        headers: { Authorization: `Bearer ${token}` }, // 发送请求时携带 Token
        withCredentials: true,
      }
    );
  };

  //发出警告模块
  const [warningView, setWarningView] = useState(false);

  const [user_id, setUser_id] = useState([]);

  const [message, setMessage] = useState([]);

  const handWarnings = () => setWarningView(true);

  const addWarning = async () => {
    await axios.post(
      "http://localhost:8848/warnings/add",
      {
        user_id: user_id,
        message: message,
      },
      {
        headers: { Authorization: `Bearer ${token}` }, // 发送请求时携带 Token
        withCredentials: true,
      }
    );
    setWarningView(false);
  };

  const banUser = async (userId) => {
    try {
      const response = await axios.put(
        `http://localhost:8848/user/ban?userid=${userId}`, // 假设后端封禁用户的接口
        {},
        {
          headers: {
            Authorization: `Bearer ${token}`, // 带上认证 token
          },
        }
      );

      if (response.status === 200) {
        alert("用户已封禁");
        fetchUserData(); // 封禁后重新获取用户数据
      } else {
        alert("封禁失败");
      }
    } catch (error) {
      console.error("封禁用户失败", error);
      alert("封禁失败");
    }
  };

  const unbanUser = async (userId) => {
    try {
      const response = await axios.put(
        `http://localhost:8848/user/unban?userid=${userId}`,
        {},
        {
          headers: {
            Authorization: `Bearer ${token}`,
          },
        }
      );
      console.log("解封成功:", response.data);
      fetchUserData(); // 解封后刷新用户列表
    } catch (error) {
      console.error("解封失败:", error);
    }
  };

  return (
    <DashboardLayout>
      <DashboardNavbar />
      <MDBox mb={2} />
      <Header>
        <MDBox mt={5} mb={3}>
          <Grid container spacing={1}>
            {/*<Grid item xs={12} md={6} xl={4}>*/}
            {/*  <PlatformSettings />*/}
            {/*</Grid>*/}
            <Grid item xs={12} md={6} xl={4} sx={{ display: "flex" }}>
              <Divider orientation="vertical" sx={{ ml: -1, mr: 1 }} />
              <div onClick={handleOpen} style={{ cursor: "pointer" }}>
                <ProfileInfoCard
                  title="个人介绍"
                  description={personalIntroduction}
                  info={{
                    email: { email },
                  }}
                  social={[
                    {
                      link: "https://www.facebook.com/CreativeTim/",
                      icon: <FacebookIcon />,
                      color: "facebook",
                    },
                    {
                      link: "https://twitter.com/creativetim",
                      icon: <TwitterIcon />,
                      color: "twitter",
                    },
                    {
                      link: "https://www.instagram.com/creativetimofficial/",
                      icon: <InstagramIcon />,
                      color: "instagram",
                    },
                  ]}
                  action={{ route: "", tooltip: "编辑简介" }}
                  shadow={false}
                />
              </div>
              <Divider orientation="vertical" sx={{ mx: 0 }} />
            </Grid>
            <Dialog open={open} onClose={handleClose}>
              <DialogTitle>编辑简介</DialogTitle>
              <DialogContent>
                <TextField
                  fullWidth
                  variant="outlined"
                  label="请输入新简介"
                  value={newBio}
                  onChange={(e) => setNewBio(e.target.value)}
                  onKeyDown={handleKeyDown} // 监听回车键提交
                  autoFocus
                />
                <TextField
                  fullWidth
                  variant="outlined"
                  label="请输入新邮箱"
                  value={newEmail}
                  onChange={(e) => setNewEmail(e.target.value)}
                  onKeyDown={handleKeyDown} // 监听回车键提交
                  autoFocus
                />
              </DialogContent>
              <DialogActions>
                <Button onClick={handleClose} color="secondary">
                  取消
                </Button>
                <Button onClick={handleSave} color="primary">
                  保存
                </Button>
              </DialogActions>
            </Dialog>
            {/*  <Grid item xs={12} xl={4}>
              <ProfilesList title="conversations" profiles={profilesListData} shadow={false} />
            </Grid>*/}
            <div onClick={handleOpenPassword}>
              <MDButton color="dark" variant="outlined" size="small">
                修改密码
              </MDButton>
            </div>
            <Dialog open={openPassword} onClose={handleClosePassword}>
              <DialogTitle>修改密码</DialogTitle>
              <DialogContent>
                <TextField
                  fullWidth
                  variant="outlined"
                  label="请输入旧密码"
                  value={oldPassword}
                  onChange={(e) => setOldPassword(e.target.value)}
                  onKeyDown={handleKeyDown} // 监听回车键提交
                  autoFocus
                />
                <TextField
                  fullWidth
                  variant="outlined"
                  label="请输入新密码"
                  value={newPassword}
                  onChange={(e) => setNewPassword(e.target.value)}
                  onKeyDown={handleKeyDown} // 监听回车键提交
                  autoFocus
                />
                <TextField
                  fullWidth
                  variant="outlined"
                  label="再输入一遍新密码"
                  value={rePassword}
                  onChange={(e) => setRePassword(e.target.value)}
                  onKeyDown={handleKeyDown} // 监听回车键提交
                  autoFocus
                />
              </DialogContent>
              <DialogActions>
                <Button onClick={handleClosePassword} color="secondary">
                  取消
                </Button>
                <Button onClick={ChangePassword} color="primary">
                  保存
                </Button>
              </DialogActions>
            </Dialog>
            {role && (
              <div onClick={fetchLogs}>
                <MDButton color="dark" variant="outlined" size="small">
                  查看日志
                </MDButton>
              </div>
            )}

            <Dialog open={showTable} onClose={() => setShowTable(false)} maxWidth="md" fullWidth>
              <DialogTitle>日志信息</DialogTitle>
              <DialogContent>
                {/* 筛选 & 排序区 */}
                <MDBox display="flex" gap={2} mb={2}>
                  <MDInput
                    label="按用户ID筛选"
                    value={filterUserId}
                    onChange={(e) => setFilterUserId(e.target.value)}
                  />
                  <MDInput
                    label="按操作筛选"
                    value={filterOperate}
                    onChange={(e) => setFilterOperate(e.target.value)}
                  />
                  <MDButton
                    onClick={() => setSortOrder(sortOrder === "asc" ? "desc" : "asc")}
                    variant="outlined"
                    color="primary"
                  >
                    按时间 {sortOrder === "asc" ? "升序" : "降序"}
                  </MDButton>
                  <MDButton
                    onClick={() => {
                      setFilterUserId("");
                      setFilterOperate("");
                    }}
                  >
                    重置
                  </MDButton>
                </MDBox>
                <MDBox>
                  <DataTable
                    table={{
                      columns,
                      rows: logData
                        .filter(
                          (item) =>
                            (!filterUserId || item.user_id?.toString().includes(filterUserId)) &&
                            (!filterOperate || item.operate?.includes(filterOperate))
                        )
                        .sort((a, b) => {
                          const timeA = new Date(a.time).getTime();
                          const timeB = new Date(b.time).getTime();
                          return sortOrder === "asc" ? timeA - timeB : timeB - timeA;
                        }),
                    }}
                    isSorted={false}
                    entriesPerPage={false}
                    showTotalEntries={false}
                    noEndBorder
                  />
                </MDBox>
              </DialogContent>
            </Dialog>
            {role && (
              <div onClick={fetchUserData}>
                <MDButton color="dark" variant="outlined" size="small">
                  查看用户列表
                </MDButton>
              </div>
            )}
            <Dialog open={showTable1} onClose={() => setShowTable1(false)} maxWidth="md" fullWidth>
              <DialogTitle>用户列表</DialogTitle>
              <DialogContent>
                <MDBox>
                  <DataTable
                    table={{
                      columns: [
                        ...columns1,
                        {
                          Header: "操作",
                          accessor: "actions", // 新增一个操作列
                          // eslint-disable-next-line react/prop-types
                          Cell: ({ row }) => (
                            <MDBox display="flex" gap={1}>
                              {/*eslint-disable-next-line react/prop-types*/}
                              {row.original.status === 1 ? (
                                <MDButton
                                  color="error"
                                  variant="contained"
                                  size="small"
                                  // eslint-disable-next-line react/prop-types
                                  onClick={() => banUser(row.original.id)}
                                >
                                  封禁
                                </MDButton>
                              ) : (
                                <MDButton
                                  color="success"
                                  variant="contained"
                                  size="small"
                                  // eslint-disable-next-line react/prop-types
                                  onClick={() => unbanUser(row.original.id)}
                                >
                                  解封
                                </MDButton>
                              )}
                            </MDBox>
                          ),
                        },
                      ],
                      rows: userData,
                    }}
                    isSorted={false}
                    entriesPerPage={false}
                    showTotalEntries={false}
                    noEndBorder
                  />
                </MDBox>
              </DialogContent>
            </Dialog>
            {role && (
              <div onClick={handWarnings}>
                <MDButton color="dark" variant="outlined" size="small">
                  发出警告
                </MDButton>
              </div>
            )}
            <Dialog
              open={warningView}
              onClose={() => setWarningView(false)}
              maxWidth="md"
              fullWidth
            >
              <DialogTitle>发出警告</DialogTitle>
              <DialogContent>
                <TextField
                  fullWidth
                  variant="outlined"
                  label="请输入你想要警告的对象id"
                  value={user_id}
                  onChange={(e) => setUser_id(e.target.value)}
                  onKeyDown={handleKeyDown}
                  autoFocus
                />
                <TextField
                  fullWidth
                  variant="outlined"
                  label="请输入你想要警告的内容"
                  value={message}
                  onChange={(e) => setMessage(e.target.value)}
                  onKeyDown={handleKeyDown}
                  autoFocus
                />
              </DialogContent>
              <DialogActions>
                <Button onClick={() => setWarningView(false)} color="secondary">
                  取消
                </Button>
                <Button onClick={addWarning} color="primary">
                  提交
                </Button>
              </DialogActions>
            </Dialog>
          </Grid>
        </MDBox>

        {/* <MDBox pt={2} px={2} lineHeight={1.25}>
          <MDTypography variant="h6" fontWeight="medium">
            Projects
          </MDTypography>
          <MDBox mb={1}>
            <MDTypography variant="button" color="text">
              Architects design houses
            </MDTypography>
          </MDBox>
        </MDBox>*/}
        {/*<MDBox p={2}>*/}
        {/*  <Grid container spacing={6}>*/}
        {/*    <PlatformSettings></PlatformSettings>*/}
        {/*<Grid item xs={12} md={6} xl={3}>*/}
        {/*  <DefaultProjectCard*/}
        {/*    image={homeDecor1}*/}
        {/*    label="project #2"*/}
        {/*    title="modern"*/}
        {/*    description="As Uber works through a huge amount of internal management turmoil."*/}
        {/*    action={{*/}
        {/*      type: "internal",*/}
        {/*      route: "/pages/profile/profile-overview",*/}
        {/*      color: "info",*/}
        {/*      label: "view project",*/}
        {/*    }}*/}
        {/*    authors={[*/}
        {/*      { image: team1, name: "Elena Morison" },*/}
        {/*      { image: team2, name: "Ryan Milly" },*/}
        {/*      { image: team3, name: "Nick Daniel" },*/}
        {/*      { image: team4, name: "Peterson" },*/}
        {/*    ]}*/}
        {/*  />*/}
        {/*</Grid>*/}
        {/*<Grid item xs={12} md={6} xl={3}>*/}
        {/*  <DefaultProjectCard*/}
        {/*    image={homeDecor2}*/}
        {/*    label="project #1"*/}
        {/*    title="scandinavian"*/}
        {/*    description="Music is something that everyone has their own specific opinion about."*/}
        {/*    action={{*/}
        {/*      type: "internal",*/}
        {/*      route: "/pages/profile/profile-overview",*/}
        {/*      color: "info",*/}
        {/*      label: "view project",*/}
        {/*    }}*/}
        {/*    authors={[*/}
        {/*      { image: team3, name: "Nick Daniel" },*/}
        {/*      { image: team4, name: "Peterson" },*/}
        {/*      { image: team1, name: "Elena Morison" },*/}
        {/*      { image: team2, name: "Ryan Milly" },*/}
        {/*    ]}*/}
        {/*  />*/}
        {/*</Grid>*/}
        {/*<Grid item xs={12} md={6} xl={3}>*/}
        {/*  <DefaultProjectCard*/}
        {/*    image={homeDecor3}*/}
        {/*    label="project #3"*/}
        {/*    title="minimalist"*/}
        {/*    description="Different people have different taste, and various types of music."*/}
        {/*    action={{*/}
        {/*      type: "internal",*/}
        {/*      route: "/pages/profile/profile-overview",*/}
        {/*      color: "info",*/}
        {/*      label: "view project",*/}
        {/*    }}*/}
        {/*    authors={[*/}
        {/*      { image: team4, name: "Peterson" },*/}
        {/*      { image: team3, name: "Nick Daniel" },*/}
        {/*      { image: team2, name: "Ryan Milly" },*/}
        {/*      { image: team1, name: "Elena Morison" },*/}
        {/*    ]}*/}
        {/*  />*/}
        {/*</Grid>*/}
        {/*<Grid item xs={12} md={6} xl={3}>*/}
        {/*  <DefaultProjectCard*/}
        {/*    image={homeDecor4}*/}
        {/*    label="project #4"*/}
        {/*    title="gothic"*/}
        {/*    description="Why would anyone pick blue over pink? Pink is obviously a better color."*/}
        {/*    action={{*/}
        {/*      type: "internal",*/}
        {/*      route: "/pages/profile/profile-overview",*/}
        {/*      color: "info",*/}
        {/*      label: "view project",*/}
        {/*    }}*/}
        {/*    authors={[*/}
        {/*      { image: team4, name: "Peterson" },*/}
        {/*      { image: team3, name: "Nick Daniel" },*/}
        {/*      { image: team2, name: "Ryan Milly" },*/}
        {/*      { image: team1, name: "Elena Morison" },*/}
        {/*    ]}*/}
        {/*  />*/}
        {/*</Grid>*/}
        {/*  </Grid>*/}
        {/*</MDBox>*/}
      </Header>
      {/* <Footer />*/}
    </DashboardLayout>
  );
}

export default Overview;
